<?php
/**
 * Created by PhpStorm.
 * User: Mars.Li
 * Date: 2015/10/21
 * Time: 12:29
 */
namespace Admin\Controller;
use Admin\Model\BalanceSheetModel;
use Admin\Model\Download;
use Admin\Model\DownloadModel;
use Admin\Model\ReportsModel;
use Admin\Model\ReportsProfitModel;
use Admin\Model\VendorModel;
use Think\Controller;

class ReportsController extends CommonController
{

    public function _before_index()
    {
        $now_year = date('Y', time());
        for ($i = $now_year - 10; $i <= $now_year + 10; $i++) {
            $years[] = array('label' => $i, 'value' => $i);
        }
        for ($i = 1; $i <= 12; $i++) {
            if ($i < 10) $i = '0' . $i;
            $months[] = array('label' => $i, 'value' => $i);
        }
        $this->assign('years', $years);
        $this->assign('months', $months);
    }

    public function index()
    {
        Vendor('U8.Api');
        $model = new ReportsModel();

        $reportlist =  $model->getRoleReportList();

        foreach ($reportlist as $report) {

            $report_name = $report['report_name'];
            $ct = $this->getCt($report_name);

            $session_year = $this->setParamData($report_name . '_year');
            $session_month = $this->setParamData($report_name . '_month');
            $session_member_company = $this->setParamData($report_name . '_member_company');
 
            
            switch ($report['report_name']) {
                case 'profit_report' :
                    //利润报表
                    $parName = '';
                    $session_year = $this->displayChildYear($session_year,$report_name);
                    $month = $session_month == '' ? date('m') - 1 : $session_month;
                    $month = $month == 0?12:$month;
                    $parName['@StarDate'] = $session_year . $month . '01';
                    $parName['@EndDate'] = $session_year . $month . '31';
                    $listarr = $model->getProfitReport($parName, $ct);
                    $this->assign('datalist', $listarr);
                    $this->assign('cols', $model->cols);
                    $this->assign('rows', $model->rows);
                    $this->assign('fristNode', $model->fristNode);
                    break;
                case 'sales_expenses_report':
                    //U8 销售额及费用表
                    $session_year = $this->displayChildYear($session_year,$report_name);
                    $this->assign('constofsales_report', $model->getConstOfSalesReport($session_year, $ct));
                    break;
                case 'center_const_report':
                    //U8中心费用汇总表
                    $session_year = $this->displayChildYear($session_year,$report_name);
                    $this->assign('eshop_consot', $model->getCenterConstReport('电商中心', $session_year, $ct));
                    $this->assign('enterprise_consot', $model->getCenterConstReport('企业中心', $session_year, $ct));
                    break;
                 case 'balance_sheet':
                    //集团销售报表
                    
                    $session_member_company = $this->setParamData($report_name . '_member_company');
                    $where['iyear'] = $session_year == ''?date('Y'):$session_year;
                    $where['U8_ZT'] = $session_member_company == '' ? '001' : $session_member_company;
                    $month = intval($session_month);
                    if ($month == ''){
                        if ((date('m') - 1) == 0) {
                            $month = 1;
                            $_SESSION['report_time'][$report_name. '_month'] = $month;
                        }else {
                            $month = date('m') - 1;
                        }
                    }
                    $where['imonth'] = array('in', $month . ',' . ($month - 1) . ',' . ($month - 2));
                    $model = new BalanceSheetModel($month);
                    $data = $model->getQmyebbData($where);
                    $where['iyear'] = $where['iyear'] - 1;
                    $where['imonth'] = 12;
                    $firstdata = $model->getQmyebbData($where);
                    $this->assign('balance_sheet', $model->getBalanceSheetHtml($data, $firstdata, $ct));
                    break;
                case 'member_profit':
                    //集团利润报表
                    $session_year = $this->displayChildYear($session_year,$report_name);
                    $session_member_company = $this->setParamData($report_name . '_member_company');
                    $where['iyear'] = $session_year;
                    $where['U8_ZT'] = $session_member_company == '' ? '001' : $session_member_company;
                    $this->assign('member_profit',$model->getMemberProfitReport($where,$ct));
                    break;
            }
        }
        $this->assign('reportlist',$reportlist);
        $this->display ();
    }

    /**
     * 设置session对象
     * @param $request_name
     * @return mixed
     */
    public function setParamData($request_name) {
        $session_data = $_SESSION['report_time'][$request_name];
        if ($session_data) $_SESSION['report_time'][$request_name] = $session_data;
        if ($_REQUEST[$request_name])
            $session_data = $_SESSION['report_time'][$request_name] = $_REQUEST[$request_name];
        return $session_data;
    }

    /**
     * 显示筛选年份
     * @param $session_year
     * @param $report_name
     * @return bool|string
     */
    public function displayChildYear($session_year,$report_name) {
            if ($session_year == '') {
                if (date('m') == 1) {
                    $session_year = date('Y') - 1;
                    $_SESSION['report_time'][$report_name. '_year'] = $session_year;
                }else {
                    $session_year = date('Y');
                }
            }
            return $session_year;
    }

    /**
     * 获取汇率和单位切换的数值
     * @param $report_name
     * @return float|int
     */
    public function getCt($report_name)
    {
        //单位为万的 需要*0.0001
        $ct = LANG_SET == 'zh-cn' ? 0.0001 : 1;
        if (session($report_name . '_unit'))
            $_SESSION[$report_name . '_unit'] = session($report_name . '_unit');
        if (isset($_REQUEST[$report_name . '_unit']))
            $_SESSION[$report_name . '_unit'] = $_REQUEST[$report_name . '_unit'];

        if ($_SESSION[$report_name . '_unit'] == 0 && isset($_SESSION[$report_name . '_unit'])) {
            $ct = 1;
        }
        //英文情况下 获取汇率
        if (LANG_SET == 'en-us') {
            $rate = getCurVal(date('Y-m', strtotime('-1 month')) . '-01');
            $ct = 1 / $rate * 0.001;
        }
        return $ct;
    }

    /**
     * 导出excel
     */
    public function exportExcel()
    {
        if (empty($_REQUEST['report_name']) || !$_REQUEST['report_name']) {
            $this->error('导出失败');
        }

        $session_year = $_SESSION['report_time'][$_REQUEST['report_name'] . '_year'];
        Vendor('U8.Api');
        $model = new ReportsModel();
        $report_name = $_REQUEST['report_name'];
        $ct = $this->getCt($report_name);

        switch ($report_name) {
            case 'profit_report' :
                $parName = '';
                if ($_SESSION['report_time']) {
                    $parName['@StarDate'] = $session_year . $_SESSION['report_time'][$_REQUEST['report_name'] . '_month'] . '01';
                    $parName['@EndDate'] = $session_year . $_SESSION['report_time'][$_REQUEST['report_name'] . '_month'] . '31';
                }
                $listarr = $model->getProfitReport($parName, $ct);
                $this->setExportFields($model->rows);
                //获取数据
                $this->setExportFileName($report_name . '_' . date('Y-m-d', time()));
                $this->setExportExcelData($listarr);
                parent::exportProfitExcel($model->cols, $model->fristNode);
                break;
            case 'sales_expenses_report':
                $field = array(
                    'month' => array('label' => '月份'),
                    'costs' => array('label' => '费用'),
                    'sales' => array('label' => '销售额'),
                );
                $this->setExportFields($field);
                //U8 销售额及费用表
                $constofsales_report = $model->getConstOfSalesReport($session_year, $ct);
                $data = array();

                foreach ($constofsales_report['costs'] as $key => $item) {
                    $data[$key]['month'] = $key + 1;
                    $data[$key]['costs'] = number_format($item['BQ_DFBB'], 1);
                    $data[$key]['sales'] = number_format($constofsales_report['sales'][$key], 1);
                }
                //获取数据
                $this->setExportFileName($report_name . '_' . date('Y-m-d', time()));
                $this->setExportExcelData($data);
                parent::exportExcel('id');
                break;
            case 'center_const_report':
                //U8中心费用汇总表
                $field = array(
                    'month' => array('label' => '月份'),
                    'cost' => array('label' => '费用'),
                    'sale' => array('label' => '销售额'),
                    'eshop_cost' => array('label' => '费用'),
                    'eshop_sale' => array('label' => '销售额'),
                );
                $this->setExportFields($field);
                $childtitle = array(
                    '', '企业', '企业', '电商', '电商'
                );
                $eshop_consot = $model->getCenterConstReport('电商中心', $session_year, $ct);
                $enterprise_consot = $model->getCenterConstReport('企业中心', $session_year, $ct);

                $costlist = array();
                foreach ($enterprise_consot['list'] as $key => $item) {
                    $costlist[$key]['month'] = $key + 1;
                    $costlist[$key]['cost'] = $item;
                    $costlist[$key]['sale'] = $enterprise_consot['sales'][$key]['BQ_DFBB'];
                    $costlist[$key]['eshop_cost'] = $eshop_consot['list'][$key];
                    $costlist[$key]['eshop_sale'] = $eshop_consot['sales'][$key]['BQ_DFBB'];
                }

                $this->setExportFileName($report_name . '_' . date('Y-m-d', time()));
                $this->setExportExcelData($costlist);
                parent::exportExcel('id', null, $childtitle);
                break;
            case 'balance_sheet':
                $where = array();
                $where['iyear'] = $session_year == '' ? date('Y') : $session_year;
                $where['U8_ZT'] = $_SESSION['report_time'][$report_name . '_member_company'] == '' ? '001' : $_SESSION['report_time'][$report_name . '_member_company'];
                $month = intval($_SESSION['report_time'][$report_name . '_month']) == '' ? date('m') - 1 : intval($_SESSION['report_time'][$report_name . '_month']);
                $where['imonth'] = array('in', $month . ',' . ($month - 1) . ',' . ($month - 2));

                if (count($where) == 0) {
                    $this->error('error');
                }
                $model = new BalanceSheetModel($month);
                $data = $model->getQmyebbData($where);
                $where['iyear'] = $where['iyear'] - 1;
                $where['imonth'] = 12;
                $firstdata = $model->getQmyebbData($where);
                $html = $model->getBalanceSheetHtml($data, $firstdata, $ct);
                parent::downloadfile($html, $report_name . '.xls');
                // make sure that write permissions are set__ROOT__.'/Public/excel'.
                //   file_put_contents('Public/excel/'.$report_name.'.xls',$html);
                break;
            case 'member_profit':
                $where = array();
                $where['iyear'] = $session_year == '' ? date('Y') : $session_year;
                $where['U8_ZT'] = $_SESSION['report_time'][$report_name . '_member_company'] == '' ? '001' : $_SESSION['report_time'][$report_name . '_member_company'];

                if (count($where) == 0) {
                    $this->error('error');
                }
                $model = new ReportsModel();
                $html= $model->getMemberProfitReport($where,$ct);
                parent::downloadfile($html, $report_name . '.xls');
                // make sure that write permissions are set__ROOT__.'/Public/excel'.
                //   file_put_contents('Public/excel/'.$report_name.'.xls',$html);
                break;
        }
    }


    public function exporExcelAll()
    {
        if (empty($_REQUEST['report_name']) || !$_REQUEST['report_name']) {
            $this->error('导出失败');
        }
        $session_year = $_SESSION['report_time'][$_REQUEST['report_name'] . '_year'];
        $report_name = $_REQUEST['report_name'];
        $ct = $this->getCt($report_name);
        $zip = new \ZipArchive();

        switch ($report_name) {
            case 'balance_sheet':
                $where = array();
                $month = intval($_SESSION['report_time'][$report_name . '_month']) == '' ? date('m') - 1 : intval($_SESSION['report_time'][$report_name . '_month']);
                $model = new BalanceSheetModel($month);

                $zippath = 'Public/excel/' .$zipname =  $report_name . '_' .date('YmdHis', time()) . '.zip';
                $filearr = array();
                if (!file_exists($zippath)) {
                    if ($zip->open($zippath, \ZipArchive::OVERWRITE)) {//创建一个空的zip文件
                        foreach (C('member_company') as $v) :
                            $where['U8_ZT'] = $v['value'];
                            $where['iyear'] = $session_year == '' ? date('Y') : $session_year;
                            $where['imonth'] = array('in', $month . ',' . ($month - 1) . ',' . ($month - 2));
                            $data = $model->getQmyebbData($where);
                            $where['iyear'] = $where['iyear'] - 1;
                            $where['imonth'] = 12;
                            $firstdata = $model->getQmyebbData($where);
                            $html = $model->getBalanceSheetHtml($data, $firstdata, $ct);
                            $filepath = 'Public/excel/' .$filename = $v['label'].'.xls';
                            //生成xls文件
                            file_put_contents($filepath, $html);
                            $filearr [] = $filepath;
                            //打包到压缩包
                            $zip->addFile($filepath,$filename);
                        endforeach;
                        $zip->close();
                    }

                    if (!file_exists($zippath)) {
                        clearFile($filearr);
                        exit("无法找到文件");
                    }
                    //下载文件
                    parent::downloadfile($zippath, basename($zipname));
                    //删除文件
                    clearFile($zippath);
                    clearFile($filearr);

                }
                break;
            case 'member_profit':
                $where = array();
                $model = new ReportsModel();

                $zipname = 'Public/excel/' . $report_name . '_' . date('YmdHis', time()) . '.zip';
                $filearr = array();
                if (!file_exists($zipname)) {
                    if ($zip->open($zipname, \ZipArchive::OVERWRITE)) {//创建一个空的zip文件
                        foreach (C('member_company') as $v) :
                            $where['U8_ZT'] = $v['value'];
                            $where['iyear'] = $session_year == '' ? date('Y') : $session_year;
                            $html= $model->getMemberProfitReport($where,$ct);
                            $filepath = 'Public/excel/' . $v['label'] . '_' . time() . '.xls';
                            //生成xls文件
                            file_put_contents($filepath, $html);
                            $filearr [] = $filepath;
                            //打包到压缩包
                            $zip->addFile($filepath, $v['label'] . '_' . time() . '.xls');
                        endforeach;
                        $zip->close();
                    }

                    if (!file_exists($zipname)) {
                        clearFile($filearr);
                        exit("无法找到文件");
                    }
                    //下载文件
                    parent::downloadfile($zipname, basename($report_name . '_' . date('YmdHis', time()) . '.zip'));
                    //删除文件
                    clearFile($zipname);
                    clearFile($filearr);
                }
                break;

        }

    }









}